package cn.fz.ssedemo.config;

import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class SseEmitterService {
    // 存储所有连接的前端客户端
    private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();

    // 用户ID -> emitter
    public void addEmitter(String userId, SseEmitter emitter) {
        emitters.put(userId, emitter);
    }

    public void removeEmitter(String userId) {
        emitters.remove(userId);
    }

    public void sendToUser(String userId, Object data){
        SseEmitter emitter = emitters.get(userId);
        if (!ObjectUtils.isEmpty(emitter)) {
            try {
                emitter.send(data);
            } catch (IOException e) {
                emitter.complete();
                emitters.remove(userId);
                // throw new RuntimeException(e);
            }
        }
    }
}
